﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class loopback : MonoBehaviour
{

	public List<GameObject> srcs;
	public double height = 0;
	public double X = 0;
	long intheight = -1;
	long intX = 0;
	long startheight = -0;
	// Use this for initialization
	void Start ()
	{
		this.Reset ();
	}

	public void Reset ()
	{
		height = 0;
		X = 0;
		intheight = -1;
		intX = 0;
		startheight = -0;
		foreach (Transform child in this.transform) {
			GameObject.Destroy (child.gameObject);
		}
		backs.Clear ();
	}

	List<SpriteRenderer> backs = new List<SpriteRenderer> ();

	GameObject RollIt ()
	{
		var i = UnityEngine.Random.Range (0, srcs.Count);
		//Debug.Log ("i=" + i);

		return GameObject.Instantiate( srcs [i]);
	}

	void UpdateHeight ()
	{
		if (srcs.Count == 0)
			return;
		
		var inth = (long)height;
		var _intx = (long)X;
		if (inth != intheight||_intx!=intX) {
			intheight = inth;
			intX = _intx;
		} else {
			return;
		}
		long useheight = startheight;
		for (var i = 0; i < 10; i++) {
			//add black

			while (backs.Count <= i) {
				GameObject obj = RollIt ();
				obj.transform.parent = this.transform;
				obj.transform.localScale =Vector3.one;
				var block = obj.GetComponent<SpriteRenderer> ();
				backs.Add (block);
			}
			//place  it;
			var c =backs [i].GetComponent<BoxCollider2D>();
			var y = backs [i].bounds.size.y;
			if (c != null) {
				 y= c.size.y;
			}


				
			backs [i].transform.localPosition = new Vector3 (intX, useheight - intheight, 0);
			useheight += (long)y;
			if((useheight -startheight )-intheight >1500)
				break;
		}
	
		var c2 =backs [0].GetComponent<BoxCollider2D>();

		var y2 = backs [0].bounds.size.y;
		if (c2 != null) {
			y2= c2.size.y;
		}
		if (backs [0].transform.localPosition.y <-300 - y2) {
			startheight += (long) y2;
			GameObject.Destroy (backs [0].gameObject);
			backs.RemoveAt (0);
		}
	}
	// Update is called once per frame
	void Update ()
	{
		//this.height += Time.deltaTime * 500;
		UpdateHeight ();
	}
}
